﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Terraria;
using TShockAPI;
using TShockAPI.DB;

namespace BeanInvsee
{
    public static class Utils
    {
        public static string GetInventoryString(Item[] items,int slots) 
        {
            StringBuilder info = new StringBuilder();
            for (int i = 0; i < slots; i++)
            {
                var item = items[i];
                if (item.netID != 0)
                {
                    if (item.prefix != 0)
                    {
                        info.Append($"[[i/p{item.prefix}:{item.netID}]]");
                    }
                    else
                    {
                        info.Append($"[[i/s{item.stack}:{item.netID}]]");
                    }

                }

            }
            return info.ToString();
        }
        public static string GetInventoryString(NetItem[] items, int slots)
        {
            StringBuilder info = new StringBuilder();
            for (int i = 0; i < slots; i++)
            {
                var item = items[i];
                if (item.NetId != 0)
                {
                    if (item.PrefixId != 0)
                    {
                        info.Append($"[[i/p{item.PrefixId}:{item.NetId}]]");
                    }
                    else
                    {
                        info.Append($"[[i/s{item.Stack}:{item.NetId}]]");
                    }

                }

            }
            return info.ToString();
        }
        public static string GetOfflinePlayerInv(IDbConnection db,string plrName) 
        {
            var id = TShock.UserAccounts.GetUserAccountID(plrName);
            using (var reader = db.QueryReader("SELECT * FROM tsCharacter WHERE Account=@0", id))
            {
                if (reader.Read())
                {

                    List<NetItem> inventory = reader.Get<string>("Inventory").Split('~').Select(NetItem.Parse).ToList();
                    if (inventory.Count < NetItem.MaxInventory)
                    {
                        //TODO: unhardcode this - stop using magic numbers and use NetItem numbers
                        //Set new armour slots empty
                        inventory.InsertRange(67, new NetItem[2]);
                        //Set new vanity slots empty
                        inventory.InsertRange(77, new NetItem[2]);
                        //Set new dye slots empty
                        inventory.InsertRange(87, new NetItem[2]);
                        //Set the rest of the new slots empty
                        inventory.AddRange(new NetItem[NetItem.MaxInventory - inventory.Count]);
                    }
                    return GetInventoryString(inventory.ToArray(), inventory.Count);
                }
                else {
                    return "";
                }
			}


		}
    }
}
